import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:hktk_app/dao/home_dao.dart';
import 'package:hktk_app/dao/industry_dao.dart';
import 'package:hktk_app/dao/subject_dao.dart';
import 'package:hktk_app/ienum/home/column_position_enum.dart';
import 'package:hktk_app/ienum/home/column_type_enum.dart';
import 'package:hktk_app/model/home/column_model.dart';
import 'package:hktk_app/model/industry/category_model.dart';
import 'package:hktk_app/model/subject/chapter_model.dart';
import 'package:hktk_app/painter/triangle_painter.dart';
import 'package:hktk_app/provider/chapter_state.dart';
import 'package:hktk_app/util/data_util.dart';
import 'package:hktk_app/util/event_bus_util.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/subject/chapter_practice_list.dart';
import 'package:hktk_app/widget/tree/chapter_tree.dart';
import 'package:provider/provider.dart';

class QuestionPage extends StatefulWidget {
  const QuestionPage({Key? key}) : super(key: key);

  @override
  _QuestionPageState createState() => _QuestionPageState();
}

class _QuestionPageState extends State<QuestionPage>
    with AutomaticKeepAliveClientMixin {
  final List<String> icons = [
    "images/question/icon1.svg",
    "images/question/icon2.svg",
    "images/question/icon3.svg",
    "images/question/icon4.svg",
    "images/question/icon5.svg",
    "images/question/icon6.svg",
    "images/question/icon7.svg"
  ];
  late List<CategoryModel> categoryList = [];
  late int selectedCategoryIndex = 0;
  late List<ColumnModel> columns = [];
  late ColumnModel? chapter;
  late int topLevel = 0;

  late List<ChapterModel>? chapterList = null;

  late Map<String, ChapterModel> allNodes = {};

  // 需要有一棵树节点管理所有的展开收合状态，节点必须有唯一key值,chapter根据parent和leaf字段
  late StreamController<bool> _expandedController;
  late StreamSubscription<EventChapterBack> _eventChapterBack;
  late StreamSubscription<ChapterModel> _eventClickChapter;

  @override
  void initState() {
    //   initState
    super.initState();
    _expandedController = StreamController();
    _expandedController.stream.listen((event) {
      if (mounted && event) {
        setState(() {});
      }
    });

    //   获取栏目,如果有章节练习再获取章节练习
    categoryList = IndustryDao.getCategoryModelsSel();

    Future.wait([
      HomeDao.columnByCategory(
          categoryId: categoryList[selectedCategoryIndex].id!,
          groupId: 6,
          columnEnum: ColumnPositionEnum.jgqy),
      HomeDao.columnByCategory(
          categoryId: categoryList[selectedCategoryIndex].id!,
          groupId: 6,
          columnEnum: ColumnPositionEnum.msjx)
    ]).then((res) {
      dataUtilComm.dataModel.categoryId =
          categoryList[selectedCategoryIndex].id!;
      dataUtilComm.dataModel.categoryName =
          categoryList[selectedCategoryIndex].name!;

      res[0].addAll(res[1]);
      columns = res[0].where((element) {
        return [
          ColumnTypeEnum.paperLibrary,
          ColumnTypeEnum.specialPractice,
          ColumnTypeEnum.randomFormPaper
        ].contains(element.type);
      }).toList();
      List<ColumnModel> temp = res[0].where((element) {
        return element.type == ColumnTypeEnum.chapterPractice;
      }).toList();
      if (temp.isNotEmpty) {
        if (temp.length > 1) {
          columns.addAll(temp.sublist(1, temp.length));
        }
        chapter = temp[0];
        //   再获取章节
        SubjectDao.chapterByColumnId(
                columnId: chapter!.id!,
                categoryId: categoryList[selectedCategoryIndex].id!)
            .then((res) {
          // 再获取做题数量
          SubjectDao.chapterRecordsIds(
                  industryCode: IndustryDao.getExamKey().industryId,
                  chapterIds: res.map((e) => e.id!).toList(),
                  examId: IndustryDao.getExamKey().examId,
                  categoryId: categoryList[selectedCategoryIndex].id!)
              .then((res1) {
            // ztNum
            for (var e in res) {
              e.ztNum = res1[e.id!]["dc"];
            }
            // 如何确保context可用
            WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
              context.read<ChapterState>().update(
                    categoryId: categoryList[selectedCategoryIndex].id,
                  );
            });

            if (mounted) {
              setState(() {
                chapterList = res;
                if (chapterList!.isNotEmpty) {
                  topLevel = chapterList![0].level!;
                }
              });
            }
          });
        });
      } else {
        //   没有章节练习
        if (mounted) {
          setState(() {});
        }
      }
    });

    _eventClickChapter = eventBus.on<ChapterModel>().listen((e) {
      // 点击一次加一下
      if (!allNodes.containsKey(e.id!)) {
        allNodes[e.id!] = e;
      }
    });
    // 监听章节练习返回刷新事件
    _eventChapterBack = eventBus.on<EventChapterBack>().listen((e) {
      List<String> ids = findAncestorNodes(e.chapterId!, allNodes).map((e) {
        return e.id!;
      }).toList();
      // 刷新做题次数
      SubjectDao.chapterRecordsIds(
              industryCode: IndustryDao.getExamKey().industryId,
              chapterIds: ids,
              examId: IndustryDao.getExamKey().examId,
              categoryId: categoryList[selectedCategoryIndex].id!)
          .then((res) {
        // 获取到做题数
        // 递归更新
        updateChapterZtNum(chapterList, res, ids);
        setState(() {});
      });
    });
  }

  @override
  void dispose() {
    //   dispose
    super.dispose();
    //   初始化获取金刚区与名师精讲栏目
    _expandedController.close();
    _eventChapterBack.cancel();
    _eventClickChapter.cancel();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    // 
    return SafeArea(
        child: SingleChildScrollView(
            child: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          decoration: BoxDecoration(color: Colors.white),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                padding: EdgeInsets.only(top: 10, left: 16),
                // height: 40,
                child: GestureDetector(
                  onTap: () {
                    Navigator.pushNamed(context, "/select-exam");
                  },
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    mainAxisSize: MainAxisSize.max,
                    children: [
                      Container(

                        // decoration: BoxDecoration(
                        //   color: Colors.blue
                        // ),
                          child: Row(
                        children: [
                          Text(
                            IndustryDao.getExamKey().examName,
                            style: FontUtil.fontBlack1(16,
                                fontWeight: FontWeight.w500),
                          ),
                          hiSpace(width: 8),

                          CustomPaint(
                            painter: TrianglePainter(),
                          )
                        ],
                      )),
                      DropdownButton(

                          value: selectedCategoryIndex,
                          dropdownColor:Color(0xffE3EDFF),
                          items: [
                            for (var i = 0; i < categoryList.length; i++)
                              DropdownMenuItem<int>(
                                value: i,
                                child: Text(categoryList[i].name!),
                              )
                          ],
                          onChanged: (value) {
                            if (selectedCategoryIndex == value) {
                              return;
                            }
                            // 重新获取栏目与章节练习
                            selectedCategoryIndex = value!;

                            dataUtilComm.dataModel.categoryId =
                                categoryList[selectedCategoryIndex].id!;
                            dataUtilComm.dataModel.categoryName =
                                categoryList[selectedCategoryIndex].name!;

                            Future.wait([
                              HomeDao.columnByCategory(
                                  categoryId:
                                      categoryList[selectedCategoryIndex].id!,
                                  groupId: 6,
                                  columnEnum: ColumnPositionEnum.jgqy),
                              HomeDao.columnByCategory(
                                  categoryId:
                                      categoryList[selectedCategoryIndex].id!,
                                  groupId: 6,
                                  columnEnum: ColumnPositionEnum.msjx)
                            ]).then((res) {
                              res[0].addAll(res[1]);
                              columns = res[0].where((element) {
                                return [
                                  ColumnTypeEnum.paperLibrary,
                                  ColumnTypeEnum.specialPractice,
                                  ColumnTypeEnum.randomFormPaper
                                ].contains(element.type);
                              }).toList();
                              List<ColumnModel> temp = res[0].where((element) {
                                return element.type ==
                                    ColumnTypeEnum.chapterPractice;
                              }).toList();
                              if (mounted) {
                                context.read<ChapterState>().update(
                                      categoryId:
                                          categoryList[selectedCategoryIndex]
                                              .id,
                                    );
                              }

                              if (temp.isNotEmpty) {
                                if (temp.length > 1) {
                                  columns.addAll(temp.sublist(1, temp.length));
                                }
                                chapter = temp[0];
                                //   再获取章节
                                SubjectDao.chapterByColumnId(
                                        columnId: chapter!.id!,
                                        categoryId:
                                            categoryList[selectedCategoryIndex]
                                                .id!)
                                    .then((res) {
                                  SubjectDao.chapterRecordsIds(
                                          industryCode: IndustryDao.getExamKey()
                                              .industryId,
                                          chapterIds:
                                              res.map((e) => e.id!).toList(),
                                          examId:
                                              IndustryDao.getExamKey().examId,
                                          categoryId: categoryList[
                                                  selectedCategoryIndex]
                                              .id!)
                                      .then((res1) {
                                    for (var e in res) {
                                      e.ztNum = res1[e.id!]["dc"];
                                    }
                                    if (mounted) {
                                      setState(() {
                                        chapterList = res;
                                        if (chapterList!.isNotEmpty) {
                                          topLevel = chapterList![0].level!;
                                        }
                                      });
                                    }
                                  });
                                });
                              } else {
                                //   没有章节练习
                                if (mounted) {
                                  setState(() {});
                                }
                              }
                            });
                          })
                    ],
                  ),
                ),
              ),
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 16, vertical: 20),
                child: Wrap(
                  alignment: WrapAlignment.start,
                  runSpacing: 14,
                  spacing: 8,
                  children: [
                    for (var i = 0; i < columns.length; i++)
                      Container(
                        width: 80,
                        child: GestureDetector(
                            onTap: () {
                              if (columns[i].type ==
                                  ColumnTypeEnum.paperLibrary) {
                                // SubjectDao.paperByColumnId(size: 1, current: 100, columnId: columns[i].id!, countDetail: true).then((res){
                                //   debugPrint("");
                                // });
                                // 进入自定义显示paperLibrary页面
                                Navigator.pushNamed(
                                    context, "/paper-library-list",
                                    arguments: {
                                      "categoryId":
                                          categoryList[selectedCategoryIndex]
                                              .id,
                                      "industryId":
                                          IndustryDao.getExamKey().industryId,
                                      "examId": IndustryDao.getExamKey().examId,
                                      "columnModel": columns[i],
                                    });
                                // Navigator.pushNamed(context, "/paper-library",arguments: {
                                //   "title":columns[i].name!,
                                // });
                              } else if (columns[i].type ==
                                  ColumnTypeEnum.randomFormPaper) {
                                Navigator.pushNamed(context, "/random-mode",
                                    arguments: {
                                      "title": columns[i].name!,
                                      "columnId": columns[i].id!,
                                      "categoryId":
                                          categoryList[selectedCategoryIndex]
                                              .id,
                                    });
                              } else if (columns[i].type ==
                                  ColumnTypeEnum.chapterPractice) {
                                Navigator.push(context, MaterialPageRoute(
                                    builder: (BuildContext context) {
                                  return MultiProvider(
                                      providers: [
                                        ChangeNotifierProvider(
                                          create: (context) => ChapterState(
                                            categoryId: categoryList[
                                                    selectedCategoryIndex]
                                                .id!,
                                          ),
                                        ),
                                      ],
                                      child: ChapterPracticeList(
                                          columnModel: columns[i],
                                          categoryId: categoryList[
                                                  selectedCategoryIndex]
                                              .id!));
                                }));
                                // Navigator.pushNamed(
                                //     context, "/chapter-practice-list",
                                //     arguments: {
                                //       "columnModel": columns[i],
                                //       "categoryId":
                                //           categoryList[selectedCategoryIndex].id
                                //     });
                              } else if (columns[i].type ==
                                  ColumnTypeEnum.randomFormPaper) {
                                //   专项练习与随机组卷相似,原app也没有专项练习相关页面，先不做
                              }
                            },
                            child: Column(
                              spacing: 2,
                              children: [
                                SvgPicture.asset(
                                  icons[i % 7],
                                  width: 45,
                                ),
                                Text(
                                  columns[i].name!,
                                  style: TextStyle(fontSize: 12),
                                )
                              ],
                            )),
                      )
                  ],
                ),
              )
            ],
          ),
        ),
        Padding(
          padding: EdgeInsets.only(top: 20, bottom: 20, left: 32),
          child: Text("章节练习"),
        ),
        if (chapterList != null)
          MultiProvider(
            providers: [
              Provider<Map<String, dynamic>>(create: (context) {
                return {
                  "columnId": chapter!.id,
                  "topLevel": topLevel,
                };
              }),

              // Provider<Something>(create: (_) => Something()),
              // ChangeNotifierProvider<String?>(create:  (context)=>chapter==null?chapter!.id:null),
              // ProxyProvider<Counter, Translations>(
              //   update: (_, counter, __) => Translations(counter.value),
              // ),
            ],
            child: Container(
              margin: EdgeInsets.only(left: 16, right: 16),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(10),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  for (var i = 0; i < chapterList!.length; i++) ...[
                    Padding(
                        padding: EdgeInsets.all(8),
                        // ChapterTree必须要获取做题数量
                        child: ChapterTree(
                            free: chapterList![i].free ?? true,
                            key: ValueKey(chapterList![i].id),
                            controller: _expandedController,
                            chapter: chapterList![i])),
                    Container(
                      width: 1.sw - 32,
                      height: 5,
                      decoration: BoxDecoration(
                          color: Theme.of(context).colorScheme.surface),
                    )
                  ]
                ],
              ),
            ),
          )
      ],
    )));
  }

  /// [孙 父 爷]
  List<ChapterModel> findAncestorNodes(
      String nodeId, Map<String, ChapterModel> allNodes) {
    List<ChapterModel> ancestors = [];

    void _findParent(String? currentId) {
      if (currentId == null || !allNodes.containsKey(currentId)) return;

      ancestors.add(allNodes[currentId]!);

      ChapterModel currentNode = allNodes[currentId]!;
      String? parentId = currentNode.parentId;

      if (parentId != "0" && allNodes.containsKey(parentId)) {
        ancestors.add(allNodes[parentId]!);
        _findParent(parentId);
      } else if (parentId == null) {}
    }

    _findParent(nodeId);
    return ancestors;
  }

  void updateChapterZtNum(List<ChapterModel>? chapters,
      Map<String, dynamic> res, List<String> ids) {
    if (chapters == null) return;

    for (var chapter in chapters) {
      // if(ids.contains(chapter.id)){
      //   e.ztNum = res[e.id!]["dc"];
      // }
      if (res.containsKey(chapter.id)) {
        chapter.ztNum = res[chapter.id!]["dc"];
      }
      if (chapter.treeChildren != null && chapter.treeChildren!.isNotEmpty) {
        updateChapterZtNum(chapter.treeChildren, res, ids);
      }
    }
  }

  @override
  //   wantKeepAlive
  bool get wantKeepAlive => true;
}
